package com.movitech.mobile.cz.base.purchase.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.DateUtils;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.purchase.bizvo.DealRequestVO;
import com.movitech.mobile.cz.base.purchase.bizvo.PSpPlanConfirmProcReqvo;
import com.movitech.mobile.cz.base.purchase.entity.PPlanChanges;
import com.movitech.mobile.cz.base.purchase.entity.PSpPlanConfirmProc;
import com.movitech.mobile.cz.base.purchase.entity.PSpecialPurchasePlan;
import com.movitech.mobile.cz.base.purchase.mapper.PSpPlanConfirmProcMapper;
import com.movitech.mobile.cz.base.purchase.service.PPlanChangesService;
import com.movitech.mobile.cz.base.purchase.service.PSpPlanConfirmProcService;
import com.movitech.mobile.cz.base.purchase.service.PSpecialPurchasePlanService;
import com.movitech.mobile.cz.base.supplier.entity.SCommentConfig;
import com.movitech.mobile.cz.base.supplier.entity.SHistoryComment;
import com.movitech.mobile.cz.base.supplier.entity.SMyDeals;
import com.movitech.mobile.cz.base.supplier.service.SCommentConfigService;
import com.movitech.mobile.cz.base.supplier.service.SHistoryCommentService;
import com.movitech.mobile.cz.base.supplier.service.SMyDealsService;
import com.movitech.mobile.cz.base.sys.entity.SProject;
import com.movitech.mobile.cz.base.sys.service.SProjectService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.List;

/**
 * <p>
 * 专项采购计划-专项采购计划确认 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-08
 */
@Service
@Transactional
public class PSpPlanConfirmProcServiceImpl extends ServiceImpl<PSpPlanConfirmProcMapper, PSpPlanConfirmProc>
		implements PSpPlanConfirmProcService {

		@Autowired
		private PSpPlanConfirmProcService pSpPlanConfirmProcService;
		@Autowired
		private PSpecialPurchasePlanService pSpecialPurchasePlanService;
		@Autowired
		private SMyDealsService sMyDealsService;
		@Autowired
		private SHistoryCommentService sHistoryCommentService;
		@Autowired
		private SCommentConfigService sCommentConfigService;
		@Autowired
		private SProjectService sProjectService;
		@Autowired
		private PPlanChangesService pPlanChangesService;

		/***
		 * 发起专项采购计划确认 添加
		 * @param pSpPlanConfirmProcReqVo
		 * @return
		 */
		@Override
		@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
		public void buildPSpPlanConfirmProc(PSpPlanConfirmProcReqvo pSpPlanConfirmProcReqVo) {
			try{
				PSpPlanConfirmProc pSpPlanConfirmProc = new PSpPlanConfirmProc();
				pSpPlanConfirmProc.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
				BeanUtils.copyProperties(pSpPlanConfirmProcReqVo,pSpPlanConfirmProc);
				if(findConfirmationProc(pSpPlanConfirmProcReqVo.getProjectId())!=null){
					throw new RuntimeException("选择项目处于确认中状态，无法再次确认",new ServiceThrowable());
				}
				String specialPurchasePlanIds = pSpecialPurchasePlanService.getNewPlansByProjectId(pSpPlanConfirmProc.getProjectId());
				if(StringUtils.isBlank(specialPurchasePlanIds)){
					throw new RuntimeException("无待确认计划",new ServiceThrowable());
				}

				pSpPlanConfirmProc.setConfirmFlag(PurchaseCommonEnum.PURCHASE_PLAN_PROC_CONFIRM_STATUS_ING.getCode());
				pSpPlanConfirmProc.setSpecialPurchasePlanIds(specialPurchasePlanIds);
				pSpPlanConfirmProcService.insert(pSpPlanConfirmProc);
				addUserDeals(pSpPlanConfirmProc.getProjectFiveThreeUserIds(),
						buildLaunchPsplanConfirm(pSpPlanConfirmProc));
				addLaunchPsplanConfirmHistory(pSpPlanConfirmProc);
				SHistoryComment sHistoryComment = buildPsplanConfirmHistory(pSpPlanConfirmProc.getId(),PurchaseNodeEnum.NODE_1_2.getDesc(),pSpPlanConfirmProc.getProjectFiveThreeUserIds());
				sHistoryComment.setUpdateDate(null);
				sHistoryComment.setUpdateBy(null);
				sHistoryComment.setActionName(PurchaseActionNameEnum.PURCHASE_PLAN_1_5.getDesc());
				sHistoryCommentService.insert(sHistoryComment);

				if(!pSpPlanConfirmProc.getProjectFiveThreeUserIds().equals(pSpPlanConfirmProc.getAreaUserIds())) {
					sHistoryComment.setUserId(pSpPlanConfirmProc.getAreaUserIds());
					sHistoryComment.setId(IdGenUtils.uuid());
					sHistoryComment.setNodeName(PurchaseNodeEnum.NODE_1_3.getDesc());
					sHistoryComment.setActionName(null);
					sHistoryCommentService.insert(sHistoryComment);
				}
				//更新计划状态为确认中
				updatePlanStatusConfiring(specialPurchasePlanIds, PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_2.getCode());

			}catch (RuntimeException re){
				re.printStackTrace();
				throw new RuntimeException(re.getMessage(),re.getCause());
			}
		}

		void updatePlanStatusConfiring(String specialPurchasePlanIds,int status){
			String[] s = specialPurchasePlanIds.trim().split(",");
			for(String planId :s){
				PSpecialPurchasePlan p = pSpecialPurchasePlanService.getSpecialPurchasePlanById(planId);
				p.setPlanStatus(status);
				p.setUpdateBy(UserUtils.getCurrentUserId());
				p.setUpdateDate(DateUtils.getNow());
				pSpecialPurchasePlanService.updateById(p);
			}
		}
		boolean addLaunchPsplanConfirmHistory(PSpPlanConfirmProc pSpPlanConfirmProc){
			SHistoryComment planConfirmHistory = new SHistoryComment();
			buildLaunchPsplanConfirmHistory(pSpPlanConfirmProc,planConfirmHistory);
			return sHistoryCommentService.insert(planConfirmHistory);
		}
		boolean addUserDeals(String userId,SMyDeals planConfirmDeal){
			planConfirmDeal.setUserId(userId);
			return sMyDealsService.insert(planConfirmDeal);
		}

		public SMyDeals buildLaunchPsplanConfirm(PSpPlanConfirmProc ppc){
			SProject sProject = sProjectService.selectById(ppc.getProjectId());
			SMyDeals planConfirmDeal = new SMyDeals();
			planConfirmDeal.setBaseFeilds(ppc.getCreateBy(), "", CommonConstants.DEL_FLAG_NORMAL, true);
			planConfirmDeal.setDealType(DealTypeEnum.PURCHASE.getCode());
			planConfirmDeal.setDealSubType(MyDealSubTypeEnum.LAUNCH_PSPLAN_CONFIRM.getCode());
			planConfirmDeal.setRelatedId(ppc.getId());
			SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.PURCHASE_INTRANET_ADD_DEAL_LAUNCH_PSPLAN_CONFIRM.getCode());

			planConfirmDeal.setDealTitle(sc==null?"": MessageFormat.format(sc.getConfigValue(),sProject.getProjectName()));
			planConfirmDeal.setDoneFlag(CommonConstants.DEL_FLAG_NORMAL);
			planConfirmDeal.setActionType(MyDealActionTypeEnum.LAUNCH_PSPLAN_CONFIRM.getCode());

			return planConfirmDeal;
		}
		void buildLaunchPsplanConfirmHistory(PSpPlanConfirmProc pSpPlanConfirmProc, SHistoryComment planConfirmHistory){
			planConfirmHistory.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
//		planConfirmHistory.setModelSubType(CommonConstants.HISTORY_SUB_TYPE_TASK);
			planConfirmHistory.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType6.getCode());
			planConfirmHistory.setRelatedId(pSpPlanConfirmProc.getId());
			planConfirmHistory.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());
			SProject sProject = sProjectService.selectById(pSpPlanConfirmProc.getProjectId());
			SCommentConfig sc = sCommentConfigService.getByCode(
					CommentConfigEnum.PURCHASE_INTRANET_ADD_HISTORY_LAUNCH_PSPLAN_CONFIRM.getCode());
			String context = sc==null?"":sc.getConfigValue();
 			String projectName= sProject==null?"":sProject.getProjectName();
			planConfirmHistory.setCommentContent(MessageFormat.format(context,projectName));

			planConfirmHistory.setActionName(PurchaseActionNameEnum.PURCHASE_PLAN_1_1.getDesc());
			planConfirmHistory.setAgreeFlag(CommonConstants.DEAL_OK);
			planConfirmHistory.setSetupTime(pSpPlanConfirmProc.getCreateDate());
			planConfirmHistory.setNodeName(PurchaseNodeEnum.NODE_1_1.getDesc());

		}

		/***
		 * 专项采购计划确认
		 * @param vo
		 * @return
		 */
		@Override
		@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
		public void confirmPSpPlan(DealRequestVO vo) {
			try{
				SMyDeals sd = sMyDealsService.selectUntreatedById(vo.getId());
				PSpPlanConfirmProc pspc = pSpPlanConfirmProcService.selectById(sd.getRelatedId());
				SProject sProject = sProjectService.selectById(pspc.getProjectId());
				String projectName = sProject==null?"":sProject.getProjectName();
				String nodeName ="";
				String userId = UserUtils.getCurrentUserId();
				boolean processEnd = false;
				boolean isPass =true;
				if(vo.getAgreeFlag()==CommonConstants.DEAL_OK){
					if(pspc.getProjectFiveThreeUserIds().equals(pspc.getAreaUserIds())){
						processEnd = true;
						updatePlanStatusConfiring(pspc.getSpecialPurchasePlanIds(),
								PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode());
					}else{
						if(UserUtils.getCurrentUserId().equals(pspc.getProjectFiveThreeUserIds())){
							addUserDeals(pspc.getAreaUserIds(),buildLaunchPsplanConfirm(pspc));
						}else{
							processEnd = true;
							updatePlanStatusConfiring(pspc.getSpecialPurchasePlanIds(),
									PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode());
						}
					}
				}else{//退回为代确认
					processEnd = true;
					isPass = false;
					updatePlanStatusConfiring(pspc.getSpecialPurchasePlanIds(),PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_1.getCode());
				}
				if(processEnd){
					PSpPlanConfirmProc pspc1 = new PSpPlanConfirmProc();
					pspc1.setId(pspc.getId());
					pspc1.setConfirmFlag(PurchaseCommonEnum.PURCHASE_PLAN_PROC_CONFIRM_STATUS_END.getCode());
					updateById(pspc1);
					if(isPass){//记录计划变更相关
						String[] planIds = pspc.getSpecialPurchasePlanIds().split(",");
						List<PSpecialPurchasePlan> byIds = pSpecialPurchasePlanService.findByIds(planIds);
						for(PSpecialPurchasePlan pSpecialPurchasePlan :byIds){
							if(pSpecialPurchasePlan.getPlanPurchasePlanCmpTime().getTime()!=pSpecialPurchasePlan.getPurchasePlanConfirmTime().getTime()){//计划采购方案时间变动
								addPPlanChange(pSpecialPurchasePlan,1);
							}
							if(pSpecialPurchasePlan.getPlanCalibrationCmpTime().getTime()!=pSpecialPurchasePlan.getPlanCalibrationConfirmTime().getTime()){//计划采购方案时间变动
								addPPlanChange(pSpecialPurchasePlan,2);
							}
						}

						pSpecialPurchasePlanService.updateChangeTime(planIds);
					}

				}

				SHistoryComment where = new SHistoryComment();
				where.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType6.getCode());
				where.setRelatedId(pspc.getId());
				where.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());
				where.setUserId(userId);
				List<SHistoryComment> sHistoryComments = sHistoryCommentService.selectList(new EntityWrapper<>(where));
				SCommentConfig sc = sCommentConfigService.getByCode(
					CommentConfigEnum.PURCHASE_INTRANET_ADD_HISTORY_PSPLAN_CONFIRM.getCode());

				String context = sc==null?"":sc.getConfigValue();
				if(CollectionUtils.isEmpty(sHistoryComments)){//兼容老数据
					SHistoryComment sHistoryComment = buildPsplanConfirmHistory(pspc.getId(), nodeName, userId);
					sHistoryComment.setAgreeFlag(vo.getAgreeFlag());
					sHistoryComment.setActionName(vo.getAgreeFlag()==CommonConstants.DEAL_OK?PurchaseActionNameEnum.PURCHASE_PLAN_1_2.getDesc(): PurchaseActionNameEnum.PURCHASE_PLAN_1_3.getDesc());
					if(StringUtils.isEmpty(context))sHistoryComment.setCommentContent(vo.getMsg());
					else sHistoryComment.setCommentContent(MessageFormat.format(context,vo.getMsg(),projectName));
					sHistoryCommentService.insert(sHistoryComment);
				}else{
					SHistoryComment sUpdate = sHistoryComments.get(0);
					sUpdate.setActionName(vo.getAgreeFlag()==CommonConstants.DEAL_OK?PurchaseActionNameEnum.PURCHASE_PLAN_1_2.getDesc(): PurchaseActionNameEnum.PURCHASE_PLAN_1_3.getDesc());
					sUpdate.setAgreeFlag(vo.getAgreeFlag());
					sUpdate.setUpdateBy(userId);
					sUpdate.setUpdateDate(DateUtils.getNow());
					if(StringUtils.isEmpty(context))sUpdate.setCommentContent(vo.getMsg());
					else sUpdate.setCommentContent(MessageFormat.format(context,vo.getMsg(),projectName));
					sHistoryCommentService.updateById(sUpdate);
				}

				sMyDealsService.deleteSmyDealsById(vo.getId());
			}catch (Exception e){
				e.printStackTrace();
				throw new RuntimeException(e.getMessage(),e.getCause());
			}

		}


		void addPPlanChange(PSpecialPurchasePlan pSpecialPurchasePlan,int changeType){
			PPlanChanges pPlanChanges = new PPlanChanges();
			pPlanChanges.setPlanId(pSpecialPurchasePlan.getId());
			if(changeType==1){
				pPlanChanges.setOrginTime(pSpecialPurchasePlan.getPurchasePlanConfirmTime());
				pPlanChanges.setChangedTime(pSpecialPurchasePlan.getPlanPurchasePlanCmpTime());
			}else{
				pPlanChanges.setOrginTime(pSpecialPurchasePlan.getPlanCalibrationConfirmTime());
				pPlanChanges.setChangedTime(pSpecialPurchasePlan.getPlanCalibrationCmpTime());
			}
			pPlanChanges.setChangedDiffDays( new BigDecimal(Math.abs(DateUtils.getDistanceOfTwoDate(pPlanChanges.getOrginTime(),pPlanChanges.getChangedTime()))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			pPlanChanges.setBaseFeilds("","",0,true);
			pPlanChanges.setChangeType(changeType);
			pPlanChangesService.insert(pPlanChanges);
		}
	@Override
	public PSpPlanConfirmProc findConfirmationProc(String projectId) {
		EntityWrapper entityWrapper = new EntityWrapper();
		PSpPlanConfirmProc pSpPlanConfirmProc = new PSpPlanConfirmProc();
		pSpPlanConfirmProc.setProjectId(projectId);
		pSpPlanConfirmProc.setConfirmFlag(PurchaseCommonEnum.PURCHASE_PLAN_PROC_CONFIRM_STATUS_ING.getCode());
		entityWrapper.setEntity(pSpPlanConfirmProc);
		return selectOne(entityWrapper);
	}

	SHistoryComment buildPsplanConfirmHistory( String relateId,String nodeName,String userId){
			SHistoryComment planConfirmHistory= new SHistoryComment();
			planConfirmHistory.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
			planConfirmHistory.setModelSubType(CommonConstants.HISTORY_SUB_TYPE_TASK);
			planConfirmHistory.setNodeName(nodeName);
			planConfirmHistory.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType6.getCode());
			planConfirmHistory.setRelatedId(relateId);
			planConfirmHistory.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());
//			SCommentConfig sc = sCommentConfigService.getByCode(
//					CommentConfigEnum.PURCHASE_INTRANET_ADD_HISTORY_PSPLAN_CONFIRM.getCode());
//			planConfirmHistory.setCommentContent(sc==null?"":sc.getConfigValue());
//		sc = sCommentConfigMapper.getByCode(
//				CommentConfigEnum.PURCHASE_INTRANET_ADD_HISTORY_ACTIONNAME_PSPLAN_CONFIRM.getCode());

//			planConfirmHistory.setActionName(vo.getAgreeFlag()==CommonConstants.DEAL_OK?PurchaseActionNameEnum.PURCHASE_PLAN_1_2.getDesc():
//					PurchaseActionNameEnum.PURCHASE_PLAN_1_3.getDesc());
//			planConfirmHistory.setAgreeFlag(vo.getAgreeFlag());
			planConfirmHistory.setSetupTime(DateUtils.getNow());
			planConfirmHistory.setUserId(userId);
			return planConfirmHistory;
		}

}
